package com.jhh.util;

import com.jhh.javabean.User;
import mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Date;
import java.util.List;

public class UserTest {
    SqlSession session;
    UserMapper mapper;

    @Before//在所有test方法执行前执行
    public void before() {
        //1、创建SqlSessionFactory对象，也是单例模式的
        SqlSessionFactory factory = MyBatisUtil.getSqlSessionFactory();
        //2、创建SqlSession对象 true 自动提交事务 不写也没事
        session = factory.openSession(true);
        //3、调用session的方法namespace的名字.id
        mapper = session.getMapper(UserMapper.class);
    }

    @After//在所有test方法执行后执行
    public void after() {
        //5、关闭资源
        session.close();
    }


    @Test
    public void selectAllUser() {
        List<User> users = mapper.selectAllUser();
        for (User u : users) {
            System.out.println("查询到所有的用户数据如下: " + u);
        }
        System.out.println("---------------------------");
    }


    @Test
    public void selectById() {
        User user = mapper.selectById(5);
        System.out.println("查询到ID为5的用户数据为: " + user);
        System.out.println("---------------------------");
    }

    @Test
    public void selectLikeName() {
        List<User> users = mapper.selectLikeName("喜");
        for (User u : users) {
            System.out.println("查询到名字有“喜”用户数据为: " + u);
        }
        System.out.println("---------------------------");
    }

    @Test
    public void updateNameById() {
        mapper.updateNameById(7, "小灰灰");
        System.out.println("更改id为7的用户名为“小灰灰”");

        System.out.println("---------------------------");
    }

    //根据id修改sal值
    @Test
    public void updateSalById() {
        mapper.updateSalById(7, 1000);
        System.out.println("更改id为7的用户的薪水为“1000”");
        System.out.println("---------------------------");
    }

    @Test
    public void insertUser() {
        User u = new User();
        u.setName("懒羊羊");
        u.setSal(666);
        u.setBirthday(new Date());
        mapper.insertUser(u);
        System.out.println("插入用户数据为: " + u);
    }

    @Test
    public void deleteByArray() {
        int[] ids = {1};
        mapper.deleteByArray(ids);
        System.out.println("删除id为1的用户数据");
    }

}
